<template>
    <el-form-item label="文件" :prop="props.files">
        <el-upload
            action=""
            list-type="picture-card"
            :accept="props.accept"
            :limit="1"
            :auto-upload="false"
            :on-exceed="handleExceed"
            :before-upload="beforeUpdata"
            :on-change="handleChange"
            :file-list="uploadFileList"
            :on-remove="Remove"
            :class="{ hide: hideUpload }">
            <template #default>
                <el-icon class="upload_icon">
                    <plus />
                </el-icon>
            </template>
            <template #file="{ file }">
                <div>
                    <el-image :src="file.url"> </el-image>
                    <span class="el-upload-list__item-actions">
                        <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                            <el-icon><delete /></el-icon>
                        </span>
                    </span>
                </div>
            </template>
            <template #tip>
                <div class="el-upload__tip">
                    <span>{{ props.tips }}</span>
                </div>
            </template>
        </el-upload>
    </el-form-item>
</template>
<script setup lang="ts">
import { ref, reactive, defineProps, onUnmounted } from 'vue';
import { ElForm, ElMessage } from 'element-plus';
import { Plus, ZoomIn, Download, Delete } from '@element-plus/icons-vue';
import type { UploadFile } from 'element-plus/es/components/upload/src/upload';
import { uploadFile, uploadOss, uploadFile2 } from '@/api/common';
import { getSetionId } from '@/utils/utils';
import bus from '@/utils/bus';
import { endLoading, startLoading } from '@/utils/request';
const emit = defineEmits(['submit', 'del']);
interface Props {
    files: string;
    tips: string;
    accept: string;
}
const props = withDefaults(defineProps<Props>(), {
    files: '',
    tips: '格式支持DOC、DOCX、XLS、XLSX、PPT、PPTX、PDF格式，文件大小不超过20M',
    accept: '.DOC,.DOCX,.XLS,.XLSX,.PPT,.PPTX,.PDF'
});
const formRef = ref<InstanceType<typeof ElForm>>();
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const disabled = ref(false);
const hideUpload = ref(false);
const uploadFileList = ref([]);

const beforeUpdata = (file: any) => {
    const is2M = file.size / 1024 / 1024 <= 20;
    if (!is2M) {
        ElMessage.warning(`上传的文件最大支持20M`);
    }
    return is2M;
};
const handleRemove = (file: UploadFile) => {
    hideUpload.value = false;
    uploadFileList.value = uploadFileList.value.filter((item: any) => item.url != file.url);
    // emit('submit', uploadFileList.value)
    emit('del');
};
const Remove = (file: UploadFile, list: UploadFile[]) => {
    uploadFileList.value = list;
    emit('submit', list);
    bus.emit('empty');
};
// 上传文件
const ext = ref();
const uploadImg = async (file: any) => {
    file = file.raw;
    ext.value = file.name.substring(file.name.lastIndexOf('.'));
    const flag = beforeUpdata(file);
    if (!flag) return;
    startLoading();
    return await uploadFile2(
        {
            file,
            fileName: file.name
        },
        null,
        true
    );
};

// 长传改变
const handleChange = async (file: UploadFile, list: UploadFile[]) => {
    const existFile = list.slice(0, list.length - 1).find(f => f.name === file.name);
    if (existFile) {
        ElMessage.error('当前文件已经存在!');
        list.pop();
        return;
    }
    try {
        const data: any = await uploadImg(file);
        const last = data.url.substring(data.url.lastIndexOf('.'));
        const fileTYpe = {
            '.pdf': '/static/file/pdf.png',
            '.doc': '/static/file/doc.png',
            '.docx': '/static/file/doc.png',
            '.xls': '/static/file/xls.png',
            '.xlsx': '/static/file/xls.png',
            '.ppt': '/static/file/ppt.png',
            '.pptx': '/static/file/ppt.png'
        };
        uploadFileList.value.push({
            realurl: data.url,
            code: data.code,
            url: fileTYpe[last] || '/static/file/file.png'
        });
        uploadFileList.value = uploadFileList.value.map(el => el);
        hideUpload.value = uploadFileList.value.length >= 1;
        emit('submit', uploadFileList.value);
        endLoading();
    } catch (error) {
        endLoading();
    }
};
const handleExceed = (file: UploadFile, list: UploadFile[]) => {
    ElMessage.warning(
        `当前限制选择1个文件，本次选择了 ${file.length} 个文件，共选择了 ${file.length + list.length} 个文件`
    );
};
// 图片数据回显
const echo = (data: any) => {
    const last = data.name.substring(data.name.lastIndexOf('.'));
    const fileTYpe = {
        '.pdf': '/static/file/pdf.png',
        '.doc': '/static/file/doc.png',
        '.docx': '/static/file/doc.png',
        '.xls': '/static/file/xls.png',
        '.xlsx': '/static/file/xls.png',
        '.ppt': '/static/file/ppt.png',
        '.pptx': '/static/file/ppt.png'
    };
    uploadFileList.value.push({
        realurl: data.absolute_url,
        code: data.code,
        url: fileTYpe[last] || '/static/file/file.png'
    });
    hideUpload.value = uploadFileList.value.length >= 1;
};
// 清空数据回显
const empty = () => {
    uploadFileList.value = [];
    hideUpload.value = false;
};
// 主动暴露方法
defineExpose({ empty, echo, ext });
</script>
<style lang="scss" scoped>
.pre_img_box {
    overflow: hidden;

    .pre_image {
        display: block;
        margin: auto;
        max-height: 400px;
    }
}
</style>
<style>
.hide .el-upload--picture-card {
    display: none;
}

.upload_icon {
    width: 140px;
    height: 90px;
}
</style>
